package de.fhtrier.gdw2.ships.menu.pages;

import de.fhtrier.gdw.commons.netcode.NetConnection;
import de.fhtrier.gdw2.ships.SpaceshipGame;
import de.fhtrier.gdw2.ships.menu.MenuManager;
import de.fhtrier.gdw2.ships.menu.MenuPage;
import de.fhtrier.gdw2.ships.menu.base.IActionListener;
import de.fhtrier.gdw2.ships.menu.base.Label;
import de.fhtrier.gdw2.ships.menu.base.TextField;
import de.fhtrier.gdw2.ships.menu.base.Widget.Align;
import de.fhtrier.gdw2.ships.network.NetGame;
import de.fhtrier.gdw2.ships.utils.AssetLoader;

import org.newdawn.slick.Color;
import org.newdawn.slick.Font;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;

/**
 * Menu page: Start or Join Server
 * 
 * @author Lusito
 */
public class MenuPageConnection extends MenuPage {
	
	protected String ip;
	protected int port;
	private boolean valid;
	private Label errorLabel;
	protected TextField name;
	protected TextField server;
    
	public MenuPageConnection(final GameContainer container, final StateBasedGame game, final MenuManager menuManager, MenuPage parent, String acceptText, String titel, final String uptype)
			throws SlickException {
		super(container, game, menuManager, parent, uptype);

		ip = NetConnection.getDefaultIp();
		port = NetGame.defaultPort;
		valid = true;
		
		Font font = AssetLoader.getInstance().getFont("verdana_46");
		Font fontSmall = AssetLoader.getInstance().getFont("verdana_32");
		
        final MenuPage connecting = new MenuPageConnecting(container, game, menuManager, this);
            
		// name 
		name = TextField.create("" , 50, 200, 400, 40)
				.image(new Image("res/menu/text_bg.png"))
				.focusImage(new Image("res/menu/text_focus.png"))
				.font(fontSmall)
				.hint("PlayerName")
				.color(Color.white);
		
		addWidget(name);

		// ip + port
		server = TextField.create("", 50, 270, 400, 40)
				.image(new Image("res/menu/text_bg.png"))
				.focusImage(new Image("res/menu/text_focus.png"))
				.font(fontSmall)
				.hint("Server:port")
				.color(Color.white)
				.hintColor(Color.gray)
				.text(ip + ":" + port);
		
		addWidget(server);
		
		errorLabel = Label.create("Error!", 50, 320, 100, 20)
				.font(fontSmall)
				.color(Color.red)
				.align(Align.LEFT)
				.visible(false);
		addWidget(errorLabel);

		// accept button
		float x = 50;
		float y = 380;
		float h = font.getLineHeight() * 1.2f;
		addLeftAlignedButton(acceptText, x, y - h/2, font,
				new IActionListener() {
					public void onAction() {
						parseServerString(server.getText());
						if (valid) {
							
							server.color = Color.white;
							try {
                                if(uptype.equals("createserver")) {
                                    createServer();
                                } else {
                                    joinServer();
                                }
                                menuManager.setPage(connecting);
							} catch (SlickException e) {
								errorLabel.visible(true);
								errorLabel.text("Error: " + e.getMessage());
//								throw new RuntimeException("Fatal Error while creating the GameWorld", e);
							}
						} else
						{
							server.color = Color.red;
						}
					}
				});

		addCenteredButton("Zurück", 840, 380, font,
				new IActionListener() {
					public void onAction() {
						close();
					}
				});
	}

	protected void createServer() throws SlickException {
        game.createServer(ip, port);
        if(!SpaceshipGame.isServer())
            System.exit(-1);
	}
    
	protected void joinServer() throws SlickException {
        game.createClient(ip, port, name.getText());
        if(!SpaceshipGame.isClient())
            System.exit(-1);
	}
    
	private void parseServerString(String connection) {
		try {
			String[] parts = connection.split(":");
			ip = parts[0];
			port = Integer.parseInt(parts[1]);
			valid = true;
		} catch(NumberFormatException e) {
			valid = false;
		}
	}
}

